package com.wei.duowan.bbs.ui.activity;

import android.graphics.Bitmap;
import android.graphics.PointF;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.photoview.PhotoView;
import com.luck.picture.lib.widget.longimage.ImageSource;
import com.luck.picture.lib.widget.longimage.ImageViewState;
import com.luck.picture.lib.widget.longimage.SubsamplingScaleImageView;
import com.wei.duowan.bbs.R;
import com.wei.duowan.bbs.presenter.BasePresenter;
import com.wei.duowan.bbs.ui.adapter.BaseRecyclerViewAdapter;
import com.wei.duowan.bbs.ui.adapter.BaseViewHolder;
import com.wei.duowan.bbs.utils.Configuration;
import com.wei.duowan.bbs.utils.GlideApp;

import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 作者：赵若位
 * 时间：2019/9/23 15:12
 * 联系方式：1070138445
 * 功能：
 */
public class PictureActivity extends BaseActivity
{
    @Bind(R.id.tv_indic)
    TextView mTvIndic;
    @Bind(R.id.tv_download)
    TextView mTvDownload;
    @Bind(R.id.tv_comments)
    TextView mTvComments;
    @Bind(R.id.tv_like)
    TextView mTvLike;
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private BaseRecyclerViewAdapter mAdapter;

    private String[] urls = new String[]
            {
                    "http://p1.pstatp.com/large/tos-cn-i-0022/e767ec209f8742e4aa9e08f89d678b3c",
                    "https://p6-tt.byteimg.com/img/mosaic-legacy/244d400001e3b0a6f04c2~noop_200x353.gif",
                    "https://n.sinaimg.cn/tech/transform/629/w397h232/20190926/0183-ifaench3884115.gif",
                    "http://p3.pstatp.com/large/pgc-image/74d239e69ac3456a8ca9880425239647",
                    "http://p3.pstatp.com/large/pgc-image/8e99d6b5726746f497cec47308d52ee7",
                    "http://p1.pstatp.com/large/pgc-image/b6a3ddf0c01d470e86587731c461c58e",
                    "http://p1.pstatp.com/large/pgc-image/0c927f0c09ae43b78a4d6f4d46bf23f7",
                    "http://p3.pstatp.com/large/tos-cn-i-0022/de035eb2b9d34848a96844758fdeb51c",
                    "http://p1.pstatp.com/large/tos-cn-i-0022/23915c2d10484a68aa9a297a08139d61",
                    "http://p1.pstatp.com/large/tos-cn-i-0022/e767ec209f8742e4aa9e08f89d678b3c",
            };


    @Override
    protected BasePresenter createPresenter()
    {
        return null;
    }

    @Override
    protected int getLayoutID()
    {
        return R.layout.activity_picture;
    }


    @Override
    protected void initView()
    {
        ImmersionBar.with(this).statusBarColor(android.R.color.black).statusBarDarkFont(false)
                .init();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        PagerSnapHelper helper = new PagerSnapHelper();
        helper.attachToRecyclerView(mRecyclerView);
        mAdapter = new BaseRecyclerViewAdapter<String>(this, R.layout.layout_picture)
        {
            @Override
            protected void convert(int position, @Nullable final BaseViewHolder holder, @Nullable final String s)
            {
                /*Gif*/
                boolean isGif = s.endsWith("GIF") || s.endsWith("gif");
                if (isGif)
                {
                    PhotoView photo = holder.setVisibility(R.id.photoView, View.VISIBLE)
                            .setVisibility(R.id.longImg, View.GONE)
                            .getView(R.id.photoView);
                    GlideApp.with(mActivity)
                            .asGif()
                            .load(s)
                            .centerInside()
                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                            .into(photo);
                } else
                {
                    GlideApp.with(mActivity)
                            .asBitmap()
                            .load(s)
                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                            .into(new SimpleTarget<Bitmap>()
                            {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition)
                                {
                                    int width = resource.getWidth();
                                    int height = resource.getHeight();
                                    boolean isLongImg = height > width * 3;
                                    holder.setVisibility(R.id.photoView, isLongImg ? View.GONE : View.VISIBLE)
                                            .setVisibility(R.id.longView, isLongImg ? View.VISIBLE : View.GONE);
                                    if (isLongImg && height > Configuration.getInstance().getOpenglRender())
                                    {
                                        int overrideWidth = width * Configuration.getInstance().getOpenglRender() / height;
                                        int overrideHeight = Configuration.getInstance().getOpenglRender();
                                        final SubsamplingScaleImageView longImage = holder.getView(R.id.longView);
                                        GlideApp.with(mActivity)
                                                .asBitmap()
                                                .load(s)
                                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                                .override(overrideWidth,overrideHeight)
                                                .into(new SimpleTarget<Bitmap>()
                                                {
                                                    @Override
                                                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition)
                                                    {
                                                        displayLongPic(resource, longImage);
                                                    }
                                                });
                                    } else if (isLongImg)
                                    {
                                        SubsamplingScaleImageView longImage = holder.getView(R.id.longView);
                                        displayLongPic(resource, longImage);
                                        longImage.setOnClickListener(view -> doFinish());
                                    } else
                                    {
                                        PhotoView imageView = holder.getView(R.id.photoView);
                                        imageView.setImageBitmap(resource);
                                        imageView.getAttacher().setOnClickListener(view -> doFinish());
                                    }
                                }
                            });
                }
            }

            /**
             * 加载长图
             *
             * @param bmp
             * @param longImg
             */
            public void displayLongPic(Bitmap bmp, SubsamplingScaleImageView longImg)
            {
                longImg.setQuickScaleEnabled(true);
                longImg.setZoomEnabled(true);
                longImg.setPanEnabled(true);
                longImg.setDoubleTapZoomDuration(100);
                longImg.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
                longImg.setDoubleTapZoomDpi(SubsamplingScaleImageView.ZOOM_FOCUS_CENTER);

                longImg.setMinScale(1.0F);
                longImg.setMaxScale(5.0F);
                int scale = Configuration.getInstance().getScreenWidth() / bmp.getWidth();

                longImg.setImage(ImageSource.cachedBitmap(bmp), new ImageViewState(scale, new PointF(0, 0), 0));
            }
        };
        mAdapter.bindRecyclerView(mRecyclerView);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
        {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState)
            {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE)
                {
                    LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    mTvIndic.setText(String.format(getString(R.string.picture_indic), manager.findFirstVisibleItemPosition() + 1, mAdapter.getItemCount()));
                }
            }
        });
        setNewData(Arrays.asList(urls));
    }


    private void setNewData(@Nullable List<String> list)
    {
        if (list != null && list.size() != 0)
        {
            mAdapter.setNewData(list);
            mTvIndic.setText(String.format(getString(R.string.picture_indic), 1, mAdapter.getItemCount()));
        }
    }


    @OnClick({R.id.img_finish, R.id.img_action, R.id.tv_download, R.id.tv_comments, R.id.tv_like})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.img_finish:
                doFinish();
                break;
            case R.id.img_action:
                //TODO 分享
                alert("分享...");
                break;
            case R.id.tv_download:
                //TODO 下载
                alert("下载图片...");
                break;
            case R.id.tv_comments:
                alert("评论...");
                break;
            case R.id.tv_like:
                alert("点赞...");
                break;
        }
    }
}
